package com.xuxueli.applyModules.commont;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
/**
 * 测试初始化定时器
 */
public class SpringInitValue implements ApplicationRunner {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("欢迎来到初始化数据");
        try {
            List<TaskBasicDTO> taskBasics = new ArrayList<>();
            for (TaskBasicDTO task : taskBasics) {
                if (task.getEnableStatus() == 0) {
                    //未开启状态或超过时间限制的时间 取下一个Task
                    continue;
                }
                long currentTimeMillis = System.currentTimeMillis();
                Integer taskType = task.getTaskType();
                Long taskTime = task.getTaskTime();
                if (taskType == 0) {
                    // 定时任务时间
                    if (taskTime < currentTimeMillis) {
                        continue;
                    }
                }
                //构建 job信息
                JobDetail jobDetail = JobBuilder.newJob(TaskExecuteJob.class)
                        .withIdentity("task_job_name_" + task.getId(), "task_job_group_name")
                        .usingJobData("id", task.getId()) //设置参数（键值对）
                        .storeDurably()
                        .build();
                //分别根据不同的任务类型 0、定时任务 1、周期任务  构建 trigger
                Trigger trigger = null;
                if (taskType == 0) {
                    //定时任务 配合定时任务时间
                    trigger = TriggerBuilder.newTrigger()
                            .startNow()
                            .withIdentity("task_job_name_" + task.getId(), "task_job_group_name")
                            .startAt(new Date(taskTime))
                            .build();
                } else {
                    //周期任务  周期任务 0、cron表达式  1、按计算时间
                    Integer cycleType = task.getCycleType();
                    if (cycleType != null) {
                        switch (cycleType) {
                            case 0: {
                                // 0、cron表达式
                                trigger = TriggerBuilder.newTrigger()
                                        .startNow()
                                        .withIdentity("task_job_name_" + task.getId(), "task_job_group_name")
                                        .withSchedule(CronScheduleBuilder.cronSchedule(task.getCycleCron()))
                                        .build();
                                break;
                            }
                            case 1: {
                                // 1、按计算时间   2_ss 2秒, 2_mm 2分, 2_hh  2小时，2_dd 2天
                                String cycleCron = task.getCycleCron();
                                String[] timeArray = cycleCron.split("_");
                                Integer timeNumber = Integer.parseInt(timeArray[0]);
                                String timeUnit = timeArray[1];
                                Integer unitValue = TimeUnitEnum.getValueByCode(timeUnit);
                                trigger = TriggerBuilder.newTrigger()
                                        .withIdentity("task_job_name_" + task.getId(), "task_job_group_name")
                                        .startAt(new Date())
                                        .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(timeNumber * unitValue).repeatForever()).build();
                                break;
                            }
                            default:
                        }
                    }
                }
                //交由Scheduler安排触发
                scheduler.scheduleJob(jobDetail, trigger);
                log.info("执行结束");
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

}
